<?php

namespace young\Printer\driver;

trait FeieyunTemplate {

    private $width   = 32;
    private $content = '';
    private $text    = '';

    //获取打印内容
    public function getContent() {
        return $this->content;
    }

    //设置打印内容
    public function setContent() {
        $this->_append($this->text);
        $this->text = '';
        return $this;
    }

    //设置打印文本
    public function text($text) {
        $this->text = $text;
        return $this;
    }

    //空格填充
    public function space($len = 0, $type = 0) {
        $this->text = $this->_mb_str_pad($this->text, $len, ' ', $type);
        return $this;
    }

    //换行
    public function br() {
        $this->_append('<BR>');
        return $this;
    }

    //分割线
    public function line($text = '') {
        if ($text !== '') {
            $text = $this->_mb_str_pad($text, $this->width, '-', STR_PAD_BOTH);
        } else {
            $text = $this->_mb_str_pad('', $this->width, '-', STR_PAD_RIGHT);
        }
        $this->_append($text);
        return $this;
    }

    //切纸
    public function cut() {
        $this->_append('<CUT>');
        return $this;
    }

    //二维码
    public function qrcode($text) {
        $this->_append('<QR>' . $text . '</QR>');
        return $this;
    }

    //居中
    public function center() {
        $this->text = '<C>' . $this->text . '</C>';
        return $this;
    }

    //加粗
    public function bold() {
        $this->text = '<BOLD>' . $this->text . '</BOLD>';
        return $this;
    }

    //放大
    public function big() {
        $this->text = '<B>' . $this->text . '</B>';
        return $this;
    }

    //居中放大
    public function centerBold() {
        $this->text = '<CB>' . $this->text . '</CB>';
        return $this;
    }

    //居右
    public function right() {
        $this->text = '<RIGHT>' . $this->text . '</RIGHT>';
        return $this;
    }

    //文本裁剪
    public function strcut($len) {
        if (mb_strwidth($this->text) > $len) {
            $this->text = mb_strcut($this->text, 0, strlen($this->text) - 1);
            return $this->strcut($len);
        } else {
            return $this;
        }
    }

    private function _mb_str_pad($str, $pad_length, $pad_string, $pad_type = STR_PAD_RIGHT, $encoding = null) {
        if ($encoding === null) {
            $encoding = mb_internal_encoding();
        }
        $w = mb_strwidth($str, $encoding);
        $len = strlen($str);
        $pad_length += $len - $w;
        return str_pad($str, $pad_length, $pad_string, $pad_type);
    }

    private function _append($text = '') {
        $this->content .= $text;
        return $this;
    }

}